package cn.gzjp.modules.gas.web.api.web;

import cn.gzjp.common.config.ConfigUtils;
import cn.gzjp.common.utils.pay.PayUtils;
import cn.gzjp.common.utils.pay.XmlUtils;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.gas.entity.GasOrder;
import cn.gzjp.modules.gas.entity.GasRecharge;
import cn.gzjp.modules.gas.service.GasOrderService;
import cn.gzjp.modules.gas.service.GasRechargeService;
import cn.gzjp.modules.logis.entity.LogisDelivery;
import cn.gzjp.modules.logis.service.LogisDeliveryService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 微信支付通知
 *
 * @author zengcp
 */
@Controller
@RequestMapping(value = "${frontPath}/back")
public class WxPayBackController extends BaseController {

    @Autowired
    private GasOrderService gasOrderService;
    @Autowired
    private GasRechargeService gasRechargeService;
    @Autowired
    private LogisDeliveryService logisDeliveryService;

    @RequestMapping(value = "notify/{type}/{id}")
    @ResponseBody
    public String notify(@PathVariable(value = "type") String type, @PathVariable(value = "id") String orderId,
                         HttpServletRequest request) {
        log.info("微信支付成功回调方法 type=" + type + "|orderId=" + orderId);

        String result = null;
        try {
            List<String> lines = IOUtils.readLines(request.getInputStream());
            StringBuilder sb = new StringBuilder();
            for (String line : lines) {
                sb.append(line);
            }
            Map<String, String> params = XmlUtils.xmlToMap(sb.toString());

            String key = ConfigUtils.getProperty("mchKey");

            boolean flag = PayUtils.checkSign(params, key);

            if (flag) {
                result = PayUtils.returnXml(true, null);
                String returnCode = params.get("return_code");
                String resultCode = params.get("result_code");
                if ("1".equals(type)) {
                    GasOrder order = this.gasOrderService.get(orderId);
                    if ("SUCCESS".equals(returnCode)
                            && "SUCCESS".equals(resultCode)) {
                        String outTradeNo = params.get("out_trade_no");
                        String totalfee = params.get("total_fee");
                        String transactionId = params.get("transaction_id");
                        if (StringUtils.isNotBlank(transactionId)) {
                            order.setWxOrderId(transactionId);
                            order.setUpdateDate(new Date());
                            order.setPayStatus(1);//已支付
                            this.gasOrderService.save(order);
                            log.info("加油订单号：" + outTradeNo + ",微信订单号："
                                    + transactionId + " ,金额为：" + totalfee + "回调成功！");
                        }
                    } else {
                        log.info("本地订单为：" + orderId + "回调时候，表明该订单支付失败！");

                    }
                }
                if ("2".equals(type))  {
                    GasRecharge order = this.gasRechargeService.get(orderId);
                    if ("SUCCESS".equals(returnCode)
                            && "SUCCESS".equals(resultCode)) {
                        String outTradeNo = params.get("out_trade_no");
                        String totalfee = params.get("total_fee");
                        String transactionId = params.get("transaction_id");
                        if (StringUtils.isNotBlank(transactionId)) {
                            order.setWxOrderId(transactionId);
                            order.setUpdateDate(new Date());
                            order.setPayStatus(1);//已支付
                            this.gasRechargeService.save(order);
                            log.info("充值订单号：" + outTradeNo + ",微信订单号："
                                    + transactionId + " ,金额为：" + totalfee + "回调成功！");
                        }
                    } else {
                        log.info("本地订单为：" + orderId + "回调时候，表明该订单支付失败！");

                    }
                }
                if ("delivery1".equals(type))  {
                    log.info("更新运单订金支付情况");
                    LogisDelivery order = this.logisDeliveryService.get(orderId);
                    if ("SUCCESS".equals(returnCode)
                            && "SUCCESS".equals(resultCode)) {
                        String outTradeNo = params.get("out_trade_no");
                        String totalfee = params.get("total_fee");
                        String transactionId = params.get("transaction_id");
                        if (StringUtils.isNotBlank(transactionId)) {
                            order.setWxOrderId(transactionId);
                            order.setUpdateDate(new Date());
                            order.setPayStatus("1");//已支付
                            this.logisDeliveryService.save(order);
                            log.info("运单订单号：" + outTradeNo + ",微信订单号："
                                    + transactionId + " ,金额为：" + totalfee + "回调成功！");
                        }
                    } else {
                        log.info("本地订单为：" + orderId + "回调时候，表明该订单支付失败！");

                    }
                }
            } else {
                logger.info("本地订单为：" + orderId + "签名认证失败，可能存在攻击！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}